define([
  'jquery',
  'underscore',
  'models/File',
  'collections/Files',
  'views/View',
  'views/upload/UploadPreview',
/*  'views/upload/UploadPhotoPreview',*/
  'hbs!template/upload/drop-upload'
], function($, _, FileModel, FileCollection, View, UploadPreview, template){
  var UploadBoxView = View.extend({
    template: template,
/*    events: {
      'dragenter #dropbox':     'noopHandler',
      'dragexit #dropbox':      'noopHandler',
      'dragover #dropbox':      'noopHandler',
      'drop #dropbox':          'dropHandler'
    },
*/
    events: {
      "click input[name=upload]":  "upload"
    },
    
    initialize: function(options){
      View.prototype.initialize(options);

      _.bindAll(this,
                'noopHandler',
                'dropHandler',
                'handleFiles');
      this.collection = new FileCollection();
      this.collection.bind("add", this.renderFilePreview, this);
      this.previews = [];
      this.cache = {};
    },

    initBox: function() {
      var dropBox = document.getElementById("dropbox");
      if(dropBox) {
        dropBox.addEventListener('dragenter', this.noopHandler, false);
        dropBox.addEventListener('dragexit', this.noopHandler, false);
        dropBox.addEventListener('dragover', this.noopHandler, false);
        dropBox.addEventListener('drop', this.dropHandler, false);
      }
    },

    render: function() {
      $(this.el).html(this.template());
      if(this.cache.previewList) { // It contains the before html generated for the list preview.
        this.Logger.debug("UploadBoxView -> render -> Rendering from cache");
        var $previewList = this.$("#previewlist", this.el);
        $previewList.html(this.cache.previewList);
      } else {
        this.renderFilesPreview();
      }
      return this;
    },
    
    noopHandler: function(evt){
      console.log("nooop");
      evt.stopPropagation();
      evt.preventDefault();
    },

    dropHandler: function(evt) {
      //console.log("Drop handler!");
      // Call noopHandler
      evt.stopPropagation();
      evt.preventDefault();

      // Reset old previews
      
      // Get files from dataTransfer object.
      console.log(evt.dataTransfer);
      var files = evt.dataTransfer.files;
      if(files) {
        var count = files.length;
        if(count) {
          this.handleFiles(files);
        }

      }
    },

    renderFilesPreview: function() {
      var that = this;
      this.collection.each(function(file){
        that.renderFilePreview(file);
      });
    },

    renderFilePreview: function(file) {
      var uploadPreview = new UploadPreview({model: file, collection: this.collection});
      this.previews.push(uploadPreview);
      //var $img = $("<img></img>", {src: evt.target.result, width: '100px', height:'100px'});
      
      var $previewList = this.$("#previewlist", this.el);
      $previewList.append(uploadPreview.render().el);
      this.cache.previewList = $previewList.html();
    },
    
    handleFiles: function(files) {
      //console.log("Handle Files.");
      var count = files.length,
          $label = $("#droplabel"),
          reader,
          file,
          i;
      for(i = 0; i < count; i++) {
        file = files[i];
        reader =  new FileReader();
        // Closure to have access to the file object when the filereader onload handler is called.
        //        reader.onload = this.handleReaderLoad;
        var self = this;
        reader.onload = (function(f){
          return function(evt) {
            var fileModel = new FileModel({
              file: f,
              content: evt.target.result,
              selected: true
            });
            self.collection.add(fileModel);
          };
        })(file);
        reader.readAsDataURL(file);
        this.renderFilesPreview();
      }
    },

    getFiles: function() {
      var files = this.collection.filter(function(file){
        return file.get("selected");
      });
      return files;
    },
    
    upload: function() {
      console.log("upload");
      var i;
      for(i=0; i < this.previews.length; i++) {
        var preview = this.previews[i];
        if(preview) {
          console.log("Subiendo la preview: " + i);
          preview.upload();
        }
      }
    }    
  });

  return UploadBoxView;
});